package com.endoc.news.fragment.newslist;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.endoc.news.R;
import com.endoc.news.databinding.FragmentNewsBinding;
import com.endoc.news.fragment.base.BaseMvvmFragment;
import com.endoc.news.fragment.base.BaseMvvmModel;
import com.endoc.news.fragment.base.BaseViewModel;
import com.endoc.news.fragment.mvvm.model.IBaseModelListener;
import com.endoc.news.fragment.mvvm.model.PagingResult;
import com.endoc.news.fragment.newslist.view.ViewStatus;
import com.endoc.news.fragment.newslist.view.pictureview.PictureViewModel;
import com.endoc.news.fragment.newslist.view.titleview.TitleViewModel;
import com.endoc.news.netWoke.NetClient;
import com.endoc.news.netWoke.NewsApiInterface;
import com.endoc.news.netWoke.bean.NewsListBean;
import com.orhanobut.logger.Logger;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.SpinnerStyle;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link NewsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewsFragment extends BaseMvvmFragment<FragmentNewsBinding,NewsFragmentViewModel> implements Observer    {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "channelId";
    private static final String ARG_PARAM2 = "name";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    //private FragmentNewsBinding fragmentNewsBinding;
    //private LoadService mLoadService;//设计到webView,先不管他
    public NewsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NewsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NewsFragment newInstance(String param1, String param2) {
        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    NewsRecycleAdapter newsRecycleAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mFragmentDataBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.fragment_news, container, false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mFragmentDataBinding.recycler.setLayoutManager(linearLayoutManager);
        newsRecycleAdapter = new NewsRecycleAdapter();
        mFragmentDataBinding.recycler.setAdapter(newsRecycleAdapter);
        //fragmentNewsBinding.srl.setRefreshFooter(new BallPulseFooter(getContext()).setSpinnerStyle(SpinnerStyle.Scale));
        //fragmentNewsBinding.srl.setRefreshHeader(new Wa);
        return mFragmentDataBinding.getRoot();
    }

    //NewsListBeanModel mNewsListBeanModel;
    //List<BaseViewModel>  mBaseViewModels = new ArrayList<BaseViewModel>();
    //NewsFragmentViewModel mNewsFragmentViewModel = new NewsFragmentViewModel();
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //将viewModel添加到fragment的生命周期
        getLifecycle().addObserver(mBaseFragmentViewModel);
        mBaseFragmentViewModel.listMutableLiveData.observe(this, new Observer<List<BaseViewModel>>() {
            @Override
            public void onChanged(List<BaseViewModel> baseViewModelList) {
                mFragmentDataBinding.srl.finishLoadMore();
                mFragmentDataBinding.srl.finishRefresh();
                ((NewsRecycleAdapter)mFragmentDataBinding.recycler.getAdapter()).setData(baseViewModelList);
            }
        });

        mBaseFragmentViewModel.errorStringLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                mFragmentDataBinding.srl.finishLoadMore();
                mFragmentDataBinding.srl.finishRefresh();
            }
        });
        mBaseFragmentViewModel.mViewStatusMutableLiveData.observe(this,this);
        //有可能在做完其他操作后,才能得到这两个数,然后才能创建viewModel,所以不建议在viewModel中传递参数
        //mBaseFragmentViewModel.NewListBeanModel(mParam1,mParam2);//此处才设置参数
        //mBaseFragmentViewModel.getCache();
        //能发现是同一个对象
        //Logger.d("NewsFragment=="+mParam1 +"    "+mBaseFragmentViewModel);
        //mNewsListBeanModel  = new NewsListBeanModel(new IBaseModelListener<List<BaseViewModel>>() {

       /* mNewsListBeanModel  = new NewsListBeanModel(mParam1,mParam2);
        mNewsListBeanModel.registerModelListener(this);*/
 /*           @Override
            public void success(NewsListBean newsListBean) {
                Logger.d(newsListBean.toString());
                    if(newsListBean.showapiResBody.retCode!=0){
                        Logger.d("数据加载失败");
                    }else {
                        List<NewsListBean.Contentlist> contentlist = newsListBean.showapiResBody.pagebean.contentlist;
                        for (int i = 0; i < contentlist.size(); i++) {
                            if(contentlist.get(i).imageurls!=null&contentlist.get(i).imageurls.size()>0){
                                Logger.d("getItemViewType");
                                PictureViewModel pictureViewModel = new PictureViewModel();
                                pictureViewModel.jumpUri =contentlist.get(i).link;
                                pictureViewModel.title=contentlist.get(i).title;
                                pictureViewModel.imageUrl=contentlist.get(i).imageurls.get(0).url;
                                mBaseViewModels.add(pictureViewModel);
                                //return TYPE_HAVE_URL;
                            }else {
                                TitleViewModel titleViewModel = new TitleViewModel();
                                titleViewModel.jumpUri =contentlist.get(i).link;
                                titleViewModel.title=contentlist.get(i).title;
                                mBaseViewModels.add(titleViewModel);
                                //return TYPE_NO_URL;
                            }
                        }
                        ((NewsRecycleAdapter)fragmentNewsBinding.recycler.getAdapter()).setData(mBaseViewModels);
                    }
            }*/

        /*    @Override
            public void success(List<BaseViewModel> baseViewModelList) {

            }*/

        /*    @Override
            public void success(List<BaseViewModel> t, PagingResult... pagingResults) {
              if(pagingResults!=null&&pagingResults.length>0&&pagingResults[0].isFirstPage){
                  mBaseViewModels.clear();
                }
                mBaseViewModels.addAll(t);
                //((NewsRecycleAdapter)fragmentNewsBinding.recycler.getAdapter()).setData(baseViewModelList);
                ((NewsRecycleAdapter)fragmentNewsBinding.recycler.getAdapter()).setData(mBaseViewModels);
                fragmentNewsBinding.srl.finishLoadMore();
                fragmentNewsBinding.srl.finishRefresh();
            }

            @Override
            public void fail(Throwable e) {
                fragmentNewsBinding.srl.finishLoadMore();
                fragmentNewsBinding.srl.finishRefresh();
            }
        }

        );*/
        //mNewsListBeanModel.getCacheData();
       /* try {
            mNewsListBeanModel.loadNextPage();
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        //mNewsListBeanModel.load();

        mFragmentDataBinding.srl.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                Logger.d("onLoadMore");
                //mNewsListBeanModel.loadNextPage(mParam1,mParam2);
            /*    try {
                    mNewsListBeanModel.loadNextPage();
                } catch (Exception e) {
                    e.printStackTrace();
                }*/
                mBaseFragmentViewModel.loadNext();
            }
        });

        mFragmentDataBinding.srl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                Logger.d("onRefresh");
                //mNewsListBeanModel.refresh(mParam1,mParam2);
              /*  try {
                    mNewsListBeanModel.refresh();
                } catch (Exception e) {
                    e.printStackTrace();
                }*/
                mBaseFragmentViewModel.refresh();
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_news;
    }

    @Override
    public NewsFragmentViewModel createViewModel() {
        //保证不会重复创建ViewModel,getActivity是在此仓库中查找,参数为mParam1的NewsFragmentViewModel实例对象,如果没有就创建,有的话就不创建
        return new ViewModelProvider(getActivity(),new NewsFragmentViewModel.NewsFragmentViewModelFactory(mParam1,mParam2)).get(mParam1,NewsFragmentViewModel.class);

     /*  return new ViewModelProvider(getActivity(), new NewsListViewModel.NewsListViewModelFactory(getArguments().getString(BUNDLE_KEY_PARAM_CHANNEL_ID),getArguments().getString(BUNDLE_KEY_PARAM_CHANNEL_NAME)))
                .get(getArguments().getString(BUNDLE_KEY_PARAM_CHANNEL_ID), NewsListViewModel.class);*/
        //return new NewsFragmentViewModel(mParam1,mParam2);
    }


    @Override
    public void onChanged(Object o) {
    /*    if (o instanceof ViewStatus && mLoadService != null) {
            switch ((ViewStatus) o) {
                case LOADING:
                    mLoadService.showCallback(LoadingCallback.class);
                    break;
                case EMPTY:
                    mLoadService.showCallback(EmptyCallback.class);
                    break;
                case SHOW_CONTENT:
                    mLoadService.showSuccess();
                    break;
                case NO_MORE_DATA:
                    ToastUtil.show("没有更多了");
                    break;
                case REFRESH_ERROR:
                    if (mNewsListViewModel.dataList.getValue().size() == 0) {
                        mLoadService.showCallback(ErrorCallback.class);
                    } else {
                        ToastUtil.show(mNewsListViewModel.errorMessage.getValue().toString());
                    }
                    break;
                case LOAD_MORE_FAILED:
                    ToastUtil.show(mNewsListViewModel.errorMessage.getValue().toString());
                    break;
            }
        }*/
    }

}
